﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;


namespace OneMile.Common
{
    /// <summary>
    /// 消息日志
    /// </summary>
    public class MobileMsgLogWriter
    {
        private static object LockObject = new object();
        private const string FloderName = "MsgLogs";

        /// <summary>
        /// 消息日志路径
        /// </summary>
        public static string BaseDirectory
        {
            get;
            set;
        }

        /// <summary>
        /// 写消息日志
        /// </summary>
        /// <param name="msg">消息</param>
        public static void Write(string msg)
        {
            Write(BaseDirectory, msg);
        }

        /// <summary>
        /// 将 Message 保存指定目录
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="msg"></param>
        public static void Write(string dir, string msg)
        {
            try
            {
                if (msg == null)
                {
                    return;
                }

                string date = DateTime.Today.ToString("yyyy-MM-dd");
                string fileName = Path.Combine(Path.Combine(dir, FloderName), date + ".txt");
                string path = Path.GetDirectoryName(fileName);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                lock (LockObject)
                {
                    using (StreamWriter sw = File.AppendText(fileName))
                    {
                        sw.WriteLine("----------------------------------------------------------");
                        sw.WriteLine(msg);
                        sw.WriteLine("----------------------------------------------------------");
                        sw.WriteLine();
                        sw.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLogWriter.Write("MobileMsgLogWriter 写文件发生错误", ex);
            }
        }
    }
}